package db

import (
	"errors"
	"fmt"
	"time"

	"github.com/jinzhu/gorm"
)

type IMUser struct {
	gorm.Model
	UserName  string
	NickName  string
	Password  string
	DepartId  uint
	AvatarUrl string
	SignInfo  string
	TelNumber string
}

var User IMUser

func (u *IMUser) Add() (userId uint, err error) {
	if u.UserName == "" || u.Password == "" {
		return 0, errors.New("UserName or Password empty")
	}

	user := u.CheckHaveUserName(u.UserName)
	if user.ID > 0 {
		return user.ID, nil
	}

	if u.DepartId == 0 {
		d := &IMDepart{}
		ukn := d.CheckHaveDepartName("Unknown")
		u.DepartId = ukn.ID
	}

	err = dbIns.Create(u).Error
	if err != nil {
		return 0, err
	}
	return u.ID, nil
}

func (u *IMUser) CheckHaveUserName(userName string) (data IMUser) {
	dbIns.Where("user_name=?", userName).First(&data)
	return
}

func (u *IMUser) CheckHaveUserId(userId uint) (data IMUser) {
	dbIns.Where("id=?", userId).First(&data)
	return
}

func (u *IMUser) GetUserNameByUserId(userId uint) string {
	var data IMUser
	dbIns.Where("id=?", userId).First(&data)
	return data.UserName
}

func (u *IMUser) GetAllUser(lastTime time.Time) (userList []IMUser) {
	dbIns.Where("updated_at > ?", lastTime).Find(&userList)
	return
}

func (u *IMUser) GetUserList(user []uint) (userList []IMUser) {
	dbIns.Find(&userList, user)
	return
}

func (u *IMUser) DeleteUser(user []string) (err error) {
	tx := dbIns.Begin()

	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			err = fmt.Errorf("%v", r)
		}
	}()

	for _, userName := range user {
		if err = tx.Where("user_name=?", userName).Delete(u).Error; err != nil {
			tx.Rollback()
			return
		}
	}

	tx.Commit()
	return nil
}

func (u *IMUser) Save() {
	dbIns.Save(u)
}
